package admin

import (
	"duoke/model"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/valid"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var Goods = new(goodsCtl)

type goodsCtl struct{}

func (ctl *goodsCtl) Info(c *gin.Context) {
	req := request.JsonMap(c)
	data, err := service.Goods.GetById(gconv.Int(req["id"]), "*")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", data)
}

func (ctl *goodsCtl) List(c *gin.Context) {
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	where := "id > 0 "
	if req.Keyword != "" {
		where += "AND title like '%" + req.Keyword + "%' "
	}
	if req.State != "" {
		where += "AND state = '" + req.State + "' "
	}
	list, err := service.Goods.List(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", list)
}

func (ctl *goodsCtl) Save(c *gin.Context) {
	req := new(model.ReqGoods)
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 保存数据
	err := service.Goods.Save(c, *req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "保存成功", nil)
}
func (ctl *goodsCtl) Del(c *gin.Context) {
	var req model.ReqIds
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.Goods.Del(req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "删除成功", nil)
}

func (ctl *goodsCtl) Copy(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.Goods.Copy(c, req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "复制成功", nil)
}

func (ctl *goodsCtl) State(c *gin.Context) {
	var req model.ReqId
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	err := service.Goods.State(req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "操作成功", nil)
}
